package com.hs.dnms.action.data;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.PropertiesUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.Tools;
import com.hs.core.utils.UUIDGenerator;
import com.hs.core.utils.UploadfileUtil;
import com.hs.dnms.model.DnmsMagazine;
import com.hs.dnms.service.IDnmsMagazineService;
@Controller  
public class DataController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(DataController.class);
	private IDnmsMagazineService magazineService;
	@Autowired  
	public void setRoleService(IDnmsMagazineService magazineService) {
		this.magazineService = magazineService;
	}
	 /**
	  * 数据管理框架
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataframe.do", method = RequestMethod.GET)   
    public ModelAndView dataframe(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
        
		 return new ModelAndView("app/data/dataframe",modelMap);
		 
	 } 
	 /**
	  * 数据管理主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataListFrame.do", method = RequestMethod.GET)   
     public ModelAndView dataListFrame(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		   	
		  return new ModelAndView("app/data/datalistframe",modelMap);
		 
	 }
	 /**
	  * 数据详细信息
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/magainfo.do")   
     public ModelAndView magainfo(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String pid = request.getParameter("id");
		 System.out.println("题录信息主键：" + pid);
		 //题录信息
		 DnmsMagazine maga = (DnmsMagazine)this.magazineService.findByID(DnmsMagazine.class, new Long(pid));
		 modelMap.put("obj", maga);
		 return new ModelAndView("app/data/magainfo",modelMap);
		 
	 }
	 /**
	  * 数据管理列表
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataList.do")   
     public ModelAndView dataList(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 PageParam pageParam = new  PageParam(request,"data/dataList.do");
		 PageUtil pageUtil = null;
		 String orderName = request.getParameter("orderName");
		 String orderNum = request.getParameter("orderNum");
		 StringBuffer orderByStr = new StringBuffer(" order by ");
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("a.state").append(" desc");
		    	orderName = "a.state";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 pageParam.getConditionMap().put("orderName", orderName);
		 pageParam.getConditionMap().put("orderNum", orderNum);
		 StringBuffer searchBuffer = new StringBuffer(" select a from DnmsMagazine a where 1=1  ");
			String state = request.getParameter("state");  
			String maganame = request.getParameter("maganame");  
			String periodicalname = request.getParameter("periodicalname"); 
			request.setAttribute("state", state);
			request.setAttribute("maganame", maganame);
			request.setAttribute("periodicalname", periodicalname);
			if(StringUtils.isNotBlank(maganame)){
				searchBuffer.append(" and (a.maganame like '%").append(maganame).append("%' ");
				searchBuffer.append(" or a.titleeng like '%").append(maganame).append("%') ");
				pageParam.getConditionMap().put("maganame", maganame);
				request.setAttribute("maganame", maganame);
			}  
			if(StringUtils.isNotBlank(periodicalname)){
				pageParam.getConditionMap().put("periodicalname", periodicalname);
				searchBuffer.append(" and (a.periodicalname like '%"+periodicalname+"%') "); 
			}
//			if(StringUtils.isNotBlank(state)){
//				pageParam.getConditionMap().put("state", state);
//				if("0".equals(state)){
//					searchBuffer.append(" and (a.dataproducer is null ) "); 
//				}else if("1".equals(state)){
//					searchBuffer.append(" and (a.dataproducer is not null ) "); 
//				}
//			}
			searchBuffer.append(orderByStr);
			Map data = new HashMap();
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = magazineService.getList(pageParam);
 			data.put("dataList", pageUtil);     
		 return new ModelAndView("app/data/dataList",data);
		 
	 } 
	 /**
	  * 数据管理分配
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataDistribute.do", method = RequestMethod.GET)   
     public ModelAndView dataDistribute(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 
		 StringBuffer searchBuffer = new StringBuffer("select a.loginid,b.username from hs_account a,hs_userinfo b ,hs_accrole c "); 
		 searchBuffer.append(" where A.userid=b.id and a.id=c.accid and c.roleid=2");
		 List producerList = DBMgr.getDbUtilInst().queryList(searchBuffer.toString(),null);
		 Map data = new HashMap();
		 data.put("producerlist", producerList);
		 return new ModelAndView("app/data/datadistribute",data);
	 } 
	 /**
	  * 数据导入主页
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataImport.do", method = RequestMethod.GET)   
     public ModelAndView dataImport(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataimport",modelMap);
		 
	 } 
	 /**
	  * 数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/import.do")   
     public ModelAndView importdata(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 String filepath = SystemUtil.getClassLoaderRoot().getAbsolutePath();
		 PropertiesUtil util = new PropertiesUtil(filepath+"/global_config.properties");
		 String tempFilepath = util.getValue("tempfilepath");
		 System.out.println("开始上传文件。。。。。。。" + tempFilepath);
		 UploadfileUtil uploadfileUtil = new UploadfileUtil();
		 File destfile =  uploadfileUtil.uploadFile(request, tempFilepath);
		 response.getWriter().write("1");
	     this.readXls(destfile);
		 return new ModelAndView("app/data/dataList",modelMap);
	 } 
	 /**
	  * 数据导入
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value="/data/importdata.do")   
     public ModelAndView importXlsData(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 MultipartFile multipartFile = multipartRequest.getFile("importfile");   
		 String fileName = multipartFile.getOriginalFilename(); 
		 String webRoot = SystemUtil.getWebappRoot().toString();
		 webRoot = webRoot.replace("\\", "/") + "/temp";
		 System.out.println("webRoot::" + webRoot );
		 String sep = System.getProperty("file.separator");
		 sep = "/"; 
		 File rootDir = new File(webRoot); 
		 if (!rootDir.exists()) {
			rootDir.mkdirs(); 
		 }
		 File file = new File(webRoot + sep + fileName);
		 BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
		 bf.write(multipartFile.getBytes());
		 bf.close();
		 System.out.println("上传成功。。。。。。");
		 this.readXls(file);
	     response.getWriter().write("1");
		 return new ModelAndView("app/data/dataList",modelMap);
	 }
	 /**
	  * 数据修改
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/saveData.do", method = RequestMethod.GET)   
     public ModelAndView saveData(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataList",modelMap);
		 
	 } 
	 /**
	  * 数据删除
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/data/dataDelete.do", method = RequestMethod.GET)   
     public ModelAndView dataDelete(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         
		 return new ModelAndView("app/data/dataList",modelMap);
		 
	 } 
	 /**
	  * 读取excel文件
	  * @param file 要读取的excel文件
	  */
	 public void readXls(File file){
			HSSFWorkbook workbook = null;
			int doublecount = 0;
			try {
				FileInputStream rs = new FileInputStream(file) ;      
				workbook = new HSSFWorkbook(rs);
				int total = workbook.getNumberOfSheets(); //获取sheet个数      
		        int start = 0;
		        int end = 0 ;  
				for(int i = 0 ; i < total ; i ++){  
		            HSSFSheet sheet = workbook.getSheetAt(i);// 按索引获取sheet引用          
		            System.out.println(sheet.getSheetName());      
		            start = sheet.getFirstRowNum();  //sheet起始行索引      
		            end = sheet.getLastRowNum();//sheet起结束行索引      
		            int temp = 1;      
		            HSSFRow row = null ;      
		            HSSFCell maganame = null ;      
		            HSSFCell titleeng = null ; 
		            HSSFCell periodicalname = null ;
		            HSSFCell author = null ; 
		            HSSFCell authoreng = null ; 
		            HSSFCell authorunit = null ; 
		            HSSFCell authoradress = null ; 
		            HSSFCell keywords = null ; 
		            HSSFCell themewords = null ; 
		            HSSFCell themewordseng = null ; 
		            HSSFCell abstract_ = null ; 
		            HSSFCell fund = null ; 
		            HSSFCell classno = null ; 
		            HSSFCell year = null ; 
		            HSSFCell volume = null ; 
		            HSSFCell period = null ; 
		            HSSFCell pageno = null ; 
		            HSSFCell abstracteng = null ;
		            HSSFCell language = null ;
		            HSSFCell sourcemagazine = null ;
		            while(temp <= end){      
		            	 DnmsMagazine maga = new DnmsMagazine();
		                 row =  sheet.getRow(temp);//获取第N行表格数据     
		                 if(row != null){
		                	  maganame = row.getCell(1);//获取指定列单元格            
				                 titleeng = row.getCell(2);   
				                 periodicalname = row.getCell(3);
				                 author = row.getCell(4);
				                 authoreng = row.getCell(5);
				                 authorunit = row.getCell(6);
				                 authoradress = row.getCell(7);
				                 keywords = row.getCell(8);
				                 themewords = row.getCell(9);
				                 themewordseng = row.getCell(10);
				                 abstract_ = row.getCell(11);
				                 fund = row.getCell(12);
				                 classno = row.getCell(13);
				                 year = row.getCell(14);
				                 volume = row.getCell(15);
				                 period = row.getCell(16);
				                 pageno = row.getCell(17);
				                 abstracteng = row.getCell(18);
				                 language = row.getCell(19);
				                 sourcemagazine = row.getCell(20);
				                 if(null != maganame){
				                	 maga.setMaganame(getCell(maganame)); 
				                 }else{
				                	 maga.setMaganame("");
				                 }
				                 if(null != titleeng){
				                	 maga.setTitleeng(getCell(titleeng)); 
				                 }else{
				                	 maga.setTitleeng("");
				                 }
				                 if(null != periodicalname){
				                	 maga.setPeriodicalname(getCell(periodicalname)); 
				                 }else{
				                	 maga.setPeriodicalname("");
				                 }
				                 if(null != author){
				                	 maga.setAuthor(getCell(author)); 
				                 }else{
				                	 maga.setAuthor("");
				                 }
				                 if(null != authoreng){
				                	 maga.setAuthoreng(getCell(authoreng)); 
				                 }else{
				                	 maga.setAuthoreng("");
				                 }
				                 if(null != authorunit){
				                	 maga.setAuthorunit(getCell(authorunit)); 
				                 }else{
				                	 maga.setAuthorunit("");
				                 }
				                 if(null != authoradress){
				                	 maga.setAuthoradress(getCell(authoradress)); 
				                 }else{
				                	 maga.setAuthoradress("");
				                 }
				                 if(null != keywords){
				                	 maga.setKeywords(getCell(keywords)); 
				                 }else{
				                	 maga.setKeywords("");
				                 }
				                 if(null != themewords){
				                	 maga.setThemewords(getCell(themewords)); 
				                 }else{
				                	 maga.setThemewords("");
				                 }
				                 if(null != themewordseng){
				                	 maga.setThemewordseng(getCell(themewordseng)); 
				                 }else{
				                	 maga.setThemewordseng("");
				                 }
				                 if(null != abstract_){
				                	 maga.setAbstract_(getCell(abstract_)); 
				                 }else{
				                	 maga.setAbstract_("");
				                 }
				                 if(null != classno){
				                	 maga.setClassno(getCell(classno)); 
				                 }else{
				                	 maga.setClassno("");
				                 }
				                 if(null != fund){
				                	 maga.setFund(getCell(fund)); 
				                 }else{
				                	 maga.setFund("");
				                 }
				                 if(null != year){
				                	 maga.setYear(getCell(year)); 
				                 }else{
				                	 maga.setYear("");
				                 }
				                 if(null != volume){
				                	 maga.setVolume(getCell(volume)); 
				                 }else{
				                	 maga.setVolume("");
				                 }
				                 if(null != period){
				                	 maga.setPeriod(getCell(period)); 
				                 }else{
				                	 maga.setPeriod("");
				                 }
				                 if(null != pageno){
				                	 maga.setPageno(getCell(pageno)); 
				                 }else{
				                	 maga.setPageno("");
				                 }
				                 if(null != abstracteng){
				                	 String strtemp = getCell(abstracteng);
				                	 if(strtemp.length()>4000)
				                		 strtemp = strtemp.substring(0,4000);
				                	   maga.setAbstracteng(strtemp); 
				                 }else{
				                	 maga.setAbstracteng("");
				                 }
				                 if(null != language){
				                	 maga.setLanguage(getCell(language)); 
				                 }else{
				                	 maga.setLanguage("");
				                 }
				                 if(null != sourcemagazine){
				                	 maga.setSourcemagazine(getCell(sourcemagazine)); 
				                 }else{
				                	 maga.setSourcemagazine("");
				                 }
				                 if("".equals(maga.getPeriodicalname()) || null == maga.getPeriodicalname()){
				                	 maga.setPeriodicalname(maga.getPeriodicalnameeng());
				                 }
				                 if("".equals(maga.getAuthor()) || null == maga.getAuthor()){
				                	 maga.setAuthor(maga.getAuthoreng());
				                 }
				                 if("".equals(maga.getKeywords()) || null == maga.getKeywords()){
				                	 maga.setKeywords(maga.getKeywordseng());
				                 }
				                 if("".equals(maga.getThemewords()) || null == maga.getThemewords()){
				                	 maga.setThemewords(maga.getThemewordseng());
				                 }
				                 if("".equals(maga.getAbstract_()) || null == maga.getAbstract_()){
				                	 maga.setAbstract_(maga.getAbstracteng());
				                 }
				                 if("".equals(maga.getPeriodicalnameeng()) || null == maga.getPeriodicalnameeng()){
				                	 maga.setPeriodicalnameeng(maga.getPeriodicalname());
				                 }
				                 if("".equals(maga.getAuthoreng()) || null == maga.getAuthoreng()){
				                	 maga.setAuthoreng(maga.getAuthor());
				                 }
				                 if("".equals(maga.getKeywordseng()) || null == maga.getKeywordseng()){
				                	 maga.setKeywordseng(maga.getKeywords());
				                 }
				                 if("".equals(maga.getThemewordseng()) || null == maga.getThemewordseng()){
				                	 maga.setThemewordseng(maga.getThemewords());
				                 }
				                 if("".equals(maga.getAbstracteng()) || null == maga.getAbstracteng()){
				                	 maga.setAbstracteng(maga.getAbstract_());
				                 }
				                 StringBuffer countsql = new StringBuffer();
				                 countsql.append("select id from dnms_magazine ");
				                 countsql.append(" where maganame='");
				                 countsql.append(maga.getMaganame().replaceAll("'", "''"));
				                 countsql.append("' and periodicalname='");
				                 countsql.append(maga.getPeriodicalname().replaceAll("'", "''") + "'");
				                 String yearstr = maga.getYear();
				                 String volumestr = maga.getVolume();
				                 String periodstr = maga.getPeriod();
				                 if(null != yearstr && !"".equals(yearstr) && !"null".equals(yearstr)){
				                	 countsql.append(" and year='" + yearstr + "'");
				                 }
				                 if(null != volumestr && !"".equals(volumestr) && !"null".equals(volumestr)){
				                	 countsql.append(" and volume='" + volumestr + "'");
				                 }
				                 if(null != periodstr && !"".equals(periodstr) && !"null".equals(periodstr)){
				                	 countsql.append(" and period='" + periodstr + "'");
				                 }
 								 List accList = DBMgr.getDbUtilInst().queryList(countsql.toString(),null);  
								 int acclen = accList.size();
								 
							     if(acclen == 0){
							    	 maga.setState("0"); 
							    	 magazineService.saveObject(maga);
 							     }else {
 							    	doublecount ++;
 							    	//logger.debug("acclen:" + acclen);
							    	 Map data = (Map)accList.get(0);
								     String id = data.get("id") + "";
							    	 StringBuffer usql = new StringBuffer("update dnms_magazine set MAGANAME=?,PERIODICALNAME=?,TITLEENG=?,PERIODICALNAMEENG=?,AUTHOR=?,AUTHORENG=?,");
							    	 usql.append("AUTHORUNIT=?,AUTHORADRESS=?,KEYWORDS=?,KEYWORDSENG=?,THEMEWORDS=?,THEMEWORDSENG=?,ABSTRACT=?,ABSTRACTENG=?,LANGUAGE=?,DOCUMENTTYPE=?,");
							    	 usql.append("CLASSNO=?,FUND=?,YEAR=?,VOLUME=?,PERIOD=?,PAGENO=?,FUNDTYPE=?,THEMETYPE=?,SOURCEMAGAZINE=?");
							    	 usql.append(" where id=?");
							    	 Object[] obj = new Object[]{maga.getMaganame(),maga.getPeriodicalname(),maga.getTitleeng(),maga.getPeriodicalnameeng(),maga.getAuthor(),maga.getAuthoreng(),
							    			 maga.getAuthorunit(),maga.getAuthoradress(),maga.getKeywords(),maga.getKeywordseng(),maga.getThemewords(),maga.getThemewordseng(),maga.getAbstract_(),
							    			 maga.getAbstracteng(),maga.getLanguage(),maga.getDocumenttype(),maga.getClassno(),maga.getFund(),maga.getYear(),maga.getVolume(),maga.getPeriod(),
							    			 maga.getPageno(),maga.getFundtype(),maga.getThemetype(),maga.getSourcemagazine(),id};
							    	 DBMgr.getDbUtilInst().update(usql.toString(), obj);
							     }
		                 }
		                 temp ++ ; 
		            } 
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
			
			logger.debug("重复数据共有:" + doublecount);
	}
	public String getCell(HSSFCell cell){
		if(cell==null)return "";
		switch(cell.getCellType()){
			case HSSFCell.CELL_TYPE_NUMERIC:
				return (long)cell.getNumericCellValue() + "";
			case HSSFCell.CELL_TYPE_STRING:
				return cell.getStringCellValue();
			case HSSFCell.CELL_TYPE_FORMULA:
				return cell.getCellFormula();
			case HSSFCell.CELL_TYPE_BLANK:
				return "";
			case	HSSFCell.CELL_TYPE_BOOLEAN:
				return cell.getBooleanCellValue() + "";
			case HSSFCell.CELL_TYPE_ERROR:
	    	    return cell.getErrorCellValue() + "";
	    	default:
	    		return "";
		}
	}
	 /**
	  * 数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/dataExport.do")   
	public ModelAndView dataExport(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String path = this.exportData("");
			System.out.println("message::" + request.getRequestURL() );
			
           //  path是指欲下载的文件的路径。 
          File file  =   new  File(path);
          String filename  =  file.getName();
         //  取得文件的后缀名。 
          String ext  =  filename.substring(filename.lastIndexOf( " . " )  +   1 ).toUpperCase();
          InputStream fis  =   new  BufferedInputStream( new  FileInputStream(path));
           byte [] buffer  =   new   byte [fis.available()];
          fis.read(buffer);
          fis.close();
          response.reset();
          response.setCharacterEncoding("UTF-8");
          System.out.println("下载文件开始" +   new  String(filename.getBytes("gb2312"),"ISO-8859-1")); 
          response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
          response.addHeader( " Content-Length " ,  ""   +  file.length());
          OutputStream toClient  =   new  BufferedOutputStream(response.getOutputStream());
          response.setContentType( "application/vnd.ms-excel" );
          toClient.write(buffer);
          toClient.flush();
          toClient.close();
      }  catch  (IOException ex) {
          ex.printStackTrace();
      }
		return null;  
	} 
	 /**
	  * 数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/exportData.do")   
	public ModelAndView exportData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String path = this.exportData("");
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/vnd.ms-excel":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
     }  catch  (IOException ex) {
         ex.printStackTrace();
     }
		return null;  
	} 
	 /**
	  * 单个题录数据导出
	  * @param request
	  * @param response
	  * @return
	 * @throws Exception 
	  */
	@RequestMapping("/data/exportMagaData.do")   
	public ModelAndView exportMagaData(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		try  {
			String magaid = request.getParameter("magaid");
			String path = this.exportData(magaid);
			System.out.println("message::" + path );
			//  path是指欲下载的文件的路径。 
			response.setCharacterEncoding("UTF-8");
			File file  =   new  File(path);
			String filename  =  file.getName();
			int fileLength = (int)file.length();
			int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = request.getSession().getServletContext();
	        String              mimetype = context.getMimeType( filename );
	        byte[]   byteContents   =   new   byte[fileLength];   
	        FileInputStream fis   =   new   FileInputStream(file);   
	        int   retcd   =   fis.read(byteContents);   
	        fis.close();    
	        logger.debug("mimetype:" + mimetype);
	        response.setContentType(mimetype == null?"application/vnd.ms-excel":mimetype );
	        response.setContentLength( retcd );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("gb2312"),"ISO-8859-1") + "\"" );
	        op.write(byteContents,0,retcd); 
	        op.close();
    }  catch  (IOException ex) {
        ex.printStackTrace();
    }
		return null;  
	} 
	/**
	 * 生成题录数据文件
	 * @return 生成的文件的路径
	 */
	public String exportData(String rid){
		String message = "false";
		 try {
				HSSFWorkbook wb = new HSSFWorkbook(); 
				 HSSFSheet sheet = wb.createSheet("new sheet"); 
				 HSSFRow row = sheet.createRow((short)0); 
				 row.createCell(0).setCellValue("biaoti_qq"); 
				 row.createCell(1).setCellValue("题名"); 
				 row.createCell(2).setCellValue("英文标题"); 
				 row.createCell(3).setCellValue("刊名"); 
				 row.createCell(4).setCellValue("作者"); 
				 row.createCell(5).setCellValue("英文作者"); 
				 row.createCell(6).setCellValue("第一作者单位"); 
				 row.createCell(7).setCellValue("第一作者地址"); 
				 row.createCell(8).setCellValue("中文关键词"); 
				 row.createCell(9).setCellValue("中文主题词"); 
				 row.createCell(10).setCellValue("英文主题词"); 
				 row.createCell(11).setCellValue("中文摘要"); 
				 row.createCell(12).setCellValue("资助情况"); 
				 row.createCell(13).setCellValue("分类号"); 
				 row.createCell(14).setCellValue("年"); 
				 row.createCell(15).setCellValue("卷"); 
				 row.createCell(16).setCellValue("期"); 
				 row.createCell(17).setCellValue("页码"); 
				 row.createCell(18).setCellValue("英文摘要"); 
				 row.createCell(19).setCellValue("语种"); 
				 row.createCell(20).setCellValue("核心期刊"); 
				 CellStyle cs=wb.createCellStyle(); 
				 List accList = null;
				 if("".equals(rid)){
					 accList = DBMgr.getDbUtilInst().queryList("select * from dnms_magazine order by id",null);
				 }else{
					 accList = DBMgr.getDbUtilInst().queryList("select * from dnms_magazine where id=? order by id",new Object[]{rid});
				 }
				 
				 for(int i=0; i<accList.size(); i++){
						Map data = (Map)accList.get(i);
						HSSFRow onerow = sheet.createRow((short)(i+1)); 
						Object obj  = data.get("id");
						if(obj instanceof Long){
							System.out.println("*****************");
						}else if(obj instanceof Integer){
							System.out.println("&&&&&&&&&&&&&");
						}else if(obj instanceof Double){
							System.out.println("################");
						}
						onerow.createCell(0).setCellValue(String.valueOf(data.get("id"))); 
						onerow.createCell(1).setCellValue((String)data.get("maganame")); 
						onerow.createCell(2).setCellValue((String)data.get("titleeng")); 
						onerow.createCell(3).setCellValue((String)data.get("periodicalname")); 
						onerow.createCell(4).setCellValue((String)data.get("author")); 
						onerow.createCell(5).setCellValue((String)data.get("authoreng")); 
						onerow.createCell(6).setCellValue((String)data.get("authorunit")); 
						onerow.createCell(7).setCellValue((String)data.get("authoradress")); 
						onerow.createCell(8).setCellValue((String)data.get("keywords")); 
						 onerow.createCell(9).setCellValue((String)data.get("themewords")); 
						 onerow.createCell(10).setCellValue((String)data.get("themewordseng")); 
						 onerow.createCell(11).setCellValue((String)data.get("abstract_")); 
						 onerow.createCell(12).setCellValue((String)data.get("fund")); 
						 onerow.createCell(13).setCellValue((String)data.get("classno")); 
						 onerow.createCell(14).setCellValue((String)data.get("year")); 
						 onerow.createCell(15).setCellValue((String)data.get("volume")); 
						 onerow.createCell(16).setCellValue((String)data.get("period")); 
						 onerow.createCell(17).setCellValue((String)data.get("pageno")); 
						 onerow.createCell(18).setCellValue((String)data.get("abstracteng")); 
						 onerow.createCell(19).setCellValue((String)data.get("language"));
						 onerow.createCell(20).setCellValue((String)data.get("sourcemagazine"));
				 }	
				 String tempFilepath = SystemUtil.getWebappRoot().toString();
				 tempFilepath = tempFilepath.replace("\\", "/") + "/temp";
				 System.out.println("tempFilepath::" + tempFilepath );
				 File tempfile = new File(tempFilepath);
				 if(!tempfile.exists()){
					 tempfile.mkdirs();
				 }
				 String destfile = tempFilepath + "/" + "多囊卵巢题录数据.xls";
				 FileOutputStream fileOut = new FileOutputStream(destfile); 
				 wb.write(fileOut); 
				 fileOut.close();
				 message = destfile;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		return message;
		
	}
}
